// 页面特定的JavaScript功能

// 产品页面功能
function initProductPage() {
    // 获取产品分类
    apiRequest("https://www.mzpower.com/api/type", {}, function(data) {
        var html = '';
        $.each(data.list, function(index, item) {
            html += `
            <li style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" data-type="${item.type}">
                <a href="#"><span>${item.name}</span></a>
            </li>`;
        });
        $('#productType').html(html);
        
        if (data.list.length > 0) {
            initProduct();
            $('#productType li').click(function() {
                $('#productType li').removeClass('now');
                $(this).addClass('now');
                $('#r_title').text($(this).text());
                getProductByType($(this).data('type'));
            });
        }
    });

    function initProduct() {
        $('#r_title').text('物联网智能传感器');
        getProductByType(1);
        $('#productType li').first().addClass('now');
    }

    function getProductByType(value, page) {
        apiRequest("https://www.mzpower.com/api/list", {
            page: page || 1,
            pageSize: 9,
            type: value
        }, function(data) {
            var html = '';
            $.each(data.list, function(index, item) {
                html += `
                <li>
                    <img src="${item.imageUrl}" alt="${item.name}">
                    <div class="des">
                        <p>${item.name}</p>
                        <a href="#" onclick="goDetail(${item.id}, 'product')">+ 查看详情</a>
                    </div>
                </li>`;
            });
            $('#productList').html(html);
            setPageNation(data);
        });
    }

    // 分页功能
    let paginationData = {};
    function setPageNation(data) {
        const { page, pageSize, total } = data;
        paginationData = { page, pageSize, total };
        let pageCount = Math.ceil(total / pageSize);
        $('#pagination').empty();
        
        let html = '';
        for (let i = 0; i < pageCount; i++) {
            html += `<a href="javascript:void(0);" data-index="${i + 1}">${i + 1}</a>`;
        }
        $('#pagination').html(html);
        $('#pagination a').eq(page - 1).addClass('now');
        
        $('#pagination a').click(function() {
            $('#pagination a').removeClass('now');
            $(this).addClass('now');
            getProductByType($('#productType li.now').data('type'), $(this).data('index'));
        });
    }

    // 上一页
    window.preBefore = function() {
        let page = parseInt($('#pagination a.now').data('index'));
        page--;
        if (page < 1) page = 1;
        getProductByType($('#productType li.now').data('type'), page);
    };

    // 下一页
    window.preNext = function() {
        let page = parseInt($('#pagination a.now').data('index'));
        let maxPage = Math.ceil(paginationData.total / paginationData.pageSize);
        page++;
        if (page > maxPage) page = maxPage;
        getProductByType($('#productType li.now').data('type'), page);
    };
}

// 新闻页面功能
function initNewsPage() {
    // 获取新闻分类
    apiRequest("https://www.mzpower.com/api/news/type", {}, function(data) {
        var html = '';
        $.each(data.list, function(index, item) {
            html += `
            <li style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" data-type="${item.type}">
                <a href="#"><span>${item.name}</span></a>
            </li>`;
        });
        $('#newsTypeMenu').html(html);
        
        if (data.list.length > 0) {
            initNews();
            $('#newsTypeMenu li').click(function() {
                $('#newsTypeMenu li').removeClass('now');
                $(this).addClass('now');
                $('#newsTitle').text($(this).text());
                getNewsByType($(this).data('type'));
            });
        }
    });

    function initNews() {
        $('#newsTitle').text('公司新闻');
        getNewsByType(1);
        $('#newsTypeMenu li').first().addClass('now');
    }

    function getNewsByType(value) {
        apiRequest("https://www.mzpower.com/api/news/list", {
            page: 1,
            pageSize: 9,
            type: value
        }, function(data) {
            var html = '';
            $.each(data.list, function(index, item) {
                html += `
                <dl class="clearfix">
                    <dt><a href="#" onclick="goDetail(${item.id}, 'news')">
                        <img src="${item.descImg}" alt="${item.title}">
                    </a></dt>
                    <dd>
                        <div class="title" style="overflow: hidden;text-overflow: ellipsis;">
                            <p><a href="#" onclick="goDetail(${item.id}, 'news')">${item.title}</a></p>
                        </div>
                        <div class="des">${item.description}</div>
                        <a href="#" class="more" onclick="goDetail(${item.id}, 'news')">+ 查看详情</a>
                    </dd>
                </dl>`;
            });
            $('#newsListContent').html(html);
        });
    }
}

// 关于我们页面功能
function initAboutPage() {
    apiRequest("https://www.mzpower.com/api/models/list", {
        page: 1,
        pageSize: 10,
        parentId: 1
    }, function(data) {
        var html = '';
        $.each(data.list, function(index, item) {
            html += `
            <li style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" data-type="${item.type}">
                <a href="#"><span>${item.name}</span></a>
            </li>`;
        });
        $('#modelType').html(html);
        
        if (data.list.length > 0) {
            initModel();
            $('#modelType li').click(function() {
                $('#modelType li').removeClass('now');
                $(this).addClass('now');
                $('#r_title').text($(this).text());
                getModelByType($(this).data('type'));
            });
        }
    });

    function initModel() {
        $('#r_title').text($('#modelType li').first().text());
        getModelByType($('#modelType li').first().data('type'));
        $('#modelType li').first().addClass('now');
    }

    function getModelByType(value) {
        apiRequest("https://www.mzpower.com/api/models/detail", {
            id: value
        }, function(data) {
            if (data.list && data.list.length > 0) {
                $('#aboutUsContent').html(data.list[0].content);
            }
        });
    }
}

// 解决方案页面功能
function initServicePage() {
    apiRequest("https://www.mzpower.com/api/models/list", {
        page: 1,
        pageSize: 10,
        parentId: 2
    }, function(data) {
        var html = '';
        $.each(data.list, function(index, item) {
            html += `
            <li style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" data-type="${item.type}">
                <a href="#"><span>${item.name}</span></a>
            </li>`;
        });
        $('#serviceType').html(html);
        
        if (data.list.length > 0) {
            initService();
            $('#serviceType li').click(function() {
                $('#serviceType li').removeClass('now');
                $(this).addClass('now');
                $('#r_title').text($(this).text());
                getServiceByType($(this).data('type'));
            });
        }
    });

    function initService() {
        $('#r_title').text($('#serviceType li').first().text());
        getServiceByType($('#serviceType li').first().data('type'));
        $('#serviceType li').first().addClass('now');
    }

    function getServiceByType(value) {
        apiRequest("https://www.mzpower.com/api/models/detail", {
            id: value
        }, function(data) {
            if (data.list && data.list.length > 0) {
                $('#serviceContent').html(data.list[0].content);
            }
        });
    }
}

// 详情页面功能
function initDetailPage() {
    let paramsObj = {};
    
    // 解析URL参数
    let url = window.location.href;
    let search = url.substring(url.lastIndexOf("?") + 1);
    let reg = /([^?&=]+)=([^?&=]*)/g;
    search.replace(reg, function(rs, $1, $2) {
        let name = decodeURIComponent($1);
        let val = decodeURIComponent($2);
        paramsObj[name] = val;
        return rs;
    });

    if (paramsObj.id) {
        // 根据页面类型调用不同的API
        let apiUrl = window.location.pathname.includes('news') ? 
            "https://www.mzpower.com/api/news/detail" : 
            "https://www.mzpower.com/api/detail";
            
        apiRequest(apiUrl, { id: paramsObj.id }, function(data) {
            if (data.list && data.list.length > 0) {
                let item = data.list[0];
                let infoHtml = '';
                
                if (window.location.pathname.includes('news')) {
                    infoHtml = `
                    <div class="left-column">
                        <h1 style="text-align:center">${item.title}</h1>
                    </div>
                    <div>
                        ${item.content}
                    </div>`;
                } else {
                    infoHtml = `
                    <div class="left-column">
                        <h1>${item.name}</h1>
                        <p>${item.tips}</p>
                    </div>
                    <div class="right-column">
                        <div class="img-wrapper">
                            <img src="${item.imageUrl}" alt="${item.name}">
                        </div>
                    </div>`;
                }
                
                $('#productDetailInfo').html(infoHtml);
                $('#productDetailContent').html(item.description || item.content || '');
            }
        });
    }
}

// 联系页面功能
function initContactPage() {
    // 百度地图初始化
    if (typeof BMapGL !== 'undefined') {
        var map = new BMapGL.Map("allmap");
        var point = new BMapGL.Point(120.172019, 30.184492);
        map.centerAndZoom(point, 15);
        map.enableScrollWheelZoom(true);
        
        var scaleCtrl = new BMapGL.ScaleControl();
        map.addControl(scaleCtrl);
        
        var zoomCtrl = new BMapGL.ZoomControl();
        map.addControl(zoomCtrl);
        
        var marker = new BMapGL.Marker(point);
        map.addOverlay(marker);
        
        var opts = {
            width: 200,
            height: 100,
            title: "杭州美卓自动化有限公司",
            message: "电话:0571-85159673"
        };
        
        var infoWindow = new BMapGL.InfoWindow("地址：杭州滨江区南环路3316号2号楼3楼", opts);
        marker.addEventListener("click", function() {
            map.openInfoWindow(infoWindow, point);
        });
    }
}

// 表单验证功能
function initFormValidation() {
    window.send = function() {
        var name = document.getElementById("input1").value;
        var mail = document.getElementById("input2").value;
        var phone = document.getElementById("input3").value;
        var content = document.getElementById("input4").value;
        var code = document.getElementById("input5").value;
        
        if (name === "") {
            showLabel('label0');
            return false;
        }
        if (mail === "") {
            showLabel('label5');
            return false;
        }
        if (content === "") {
            showLabel('label10');
            return false;
        }
        if (code === "") {
            alert('请填写验证码！');
            return false;
        }
        
        alert('信息已发送到站长邮箱，感谢您的支持！');
        return true;
    };

    window.jieshou = function() {
        var nametext = document.getElementById("input1").value;
        if (nametext !== "") {
            showLabel('label1');
        } else {
            showLabel('label0');
        }
    };

    window.mailtext = function() {
        var mailvalue = document.getElementById("input2").value;
        var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        
        if (mailvalue !== "") {
            if (myreg.test(mailvalue)) {
                showLabel('label3');
            } else {
                showLabel('label4');
            }
        } else {
            showLabel('label5');
        }
    };

    window.phonetext = function() {
        var phonetext = document.getElementById("input3").value;
        if (/^1[3|4|5|7|8]\d{9}$/.test(phonetext)) {
            showLabel('label6');
        } else {
            showLabel('label7');
        }
    };

    window.content = function() {
        var content = document.getElementById("input4").value;
        if (content !== "") {
            showLabel('label8');
        } else {
            showLabel('label10');
        }
    };

    function showLabel(labelId) {
        // 隐藏所有标签
        for (let i = 0; i <= 10; i++) {
            let label = document.getElementById('label' + i);
            if (label) label.style.display = 'none';
        }
        
        // 显示指定标签
        let targetLabel = document.getElementById(labelId);
        if (targetLabel) targetLabel.style.display = 'block';
    }
}
